﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Text;
using System.Net;
using System.IO;

using Facebook;

using CE.Global;

public partial class car_insurance_get_quote_facebook_Default : Page
{
    string fb_AppID = ConfigurationManager.AppSettings["ApiKey"].ToString();
    string fb_AppSecret = ConfigurationManager.AppSettings["Secret"].ToString();
    string fb_CanvasUrl = ConfigurationManager.AppSettings["FB_CanvasUrl"].ToString();
    string fb_TestUrl = ConfigurationManager.AppSettings["FB_TestUrl"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                if (Request.Params["auth_referral"] != null && Request.Params["auth_referral"].ToString() == "1")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "JSRedirectForAuthReferral", "window.top.location.href='" + fb_CanvasUrl + "';", true);
                }
                else
                {
                    Session[General.FB_UserId] = null;
                    Session[General.UserName] = null;
                    Session[General.UserDOB] = null;
                    Session[General.UserGender] = null;
                    Session[General.UserEmail] = null;

                    if (Request.Params["signed_request"] != null)
                    {
                        if (Request.Params["code"] != null)
                        {
                            var parameters = new Dictionary<string, string>();
                            parameters.Add("client_id", fb_AppID);
                            parameters.Add("redirect_uri", fb_CanvasUrl);
                            parameters.Add("client_secret", fb_AppSecret);
                            parameters.Add("scope", "email,user_birthday");
                            parameters.Add("code", Request.Params["code"].ToString());


                            Uri baseURL = new Uri("https://graph.facebook.com");
                            Uri url = new Uri(baseURL, "/oauth/access_token");
                            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url.ToString() + EncodeDictionary(parameters, true));
                            req.Method = "GET";
                            //req.Referer = "http://www.comparexpress.com";
                            HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                            Stream stream = webResponse.GetResponseStream();
                            StreamReader answer = new StreamReader(stream);
                            string anstr = answer.ReadToEnd();

                            string _fqlStatement = "SELECT uid, email, birthday, birthday_date, contact_email, first_name, middle_name, last_name, name, locale, pic_square, profile_url, sex FROM user WHERE uid= me()";

                            FacebookAPI _fbApi = new FacebookAPI();

                            JSONObject _jsObjectToken = _fbApi.Get("/fql?q=" + _fqlStatement + "&" + anstr);

                            JSONObject _JsonUserData = null;
                            foreach (KeyValuePair<string, JSONObject> kvp in _jsObjectToken.Dictionary)
                            {
                                _JsonUserData = kvp.Value;
                                if (_JsonUserData.Array[0].IsDictionary)
                                {
                                    Response.Write("<br/>" + _JsonUserData.Array[0].Dictionary.Count + "<br/>");
                                    _JsonUserData = _JsonUserData.Array[0];
                                }
                            }

                            if (_JsonUserData != null && _JsonUserData.Dictionary != null && _JsonUserData.Dictionary.Count > 0)
                            {
                                Session[General.FB_UserId] = (_JsonUserData.Dictionary.ContainsKey("uid") ? _JsonUserData.Dictionary["uid"].String : null);
                                Session[General.UserName] = (_JsonUserData.Dictionary.ContainsKey("name") ? _JsonUserData.Dictionary["name"].String : null);
                                Session[General.UserDOB] = (_JsonUserData.Dictionary.ContainsKey("birthday_date") ? _JsonUserData.Dictionary["birthday_date"].String : null);
                                Session[General.UserGender] = (_JsonUserData.Dictionary.ContainsKey("sex") ? _JsonUserData.Dictionary["sex"].String : null);
                                Session[General.UserEmail] = (_JsonUserData.Dictionary.ContainsKey("contact_email") ? _JsonUserData.Dictionary["contact_email"].String : null);
                                if (fb_TestUrl.Length > 0)
                                {
                                    string q = "id=" + Session[General.FB_UserId].ToString() + "&email=" + Session[General.UserEmail].ToString() + "&name=" + Session[General.UserName].ToString() + "&gender=" + Session[General.UserGender].ToString();
                                    Response.Redirect(fb_TestUrl + "?" + q);
                                }
                                else
                                {
                                    Response.Redirect("carandpolicy_details.aspx");
                                }
                            }
                        }
                        else
                        {
                            string _url = "https://graph.facebook.com/oauth/authorize?client_id=" + fb_AppID + "&redirect_uri=" + fb_CanvasUrl + "";
                            ClientScript.RegisterStartupScript(this.GetType(), "JSRedirectForCode", "window.top.location.href='" + _url + "';", true);
                        }
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            Response.Write("MESSAGE:" + Ex.Message);
            Response.Write("<br/><br/>Please wait. Page is reloading...");
            string _url = "https://graph.facebook.com/oauth/authorize?client_id=" + fb_AppID + "&redirect_uri=" + fb_CanvasUrl + "&scope=email,user_birthday";
            ClientScript.RegisterStartupScript(this.GetType(), "JSRedirectForCode", "window.top.location.href='" + _url + "';", true);
        }
    }

    private string EncodeDictionary(Dictionary<string, string> dict,
                                    bool questionMark)
    {
        StringBuilder sb = new StringBuilder();
        if (questionMark)
        {
            sb.Append("?");
        }
        foreach (KeyValuePair<string, string> kvp in dict)
        {
            sb.Append(HttpUtility.UrlEncode(kvp.Key));
            sb.Append("=");
            sb.Append(HttpUtility.UrlEncode(kvp.Value));
            sb.Append("&");
        }
        sb.Remove(sb.Length - 1, 1); // Remove trailing &
        return sb.ToString();
    }
}
